/*
 * Created by 2020-12-04 12:41:48 
 */
package com.edev.support.dao.impl.utils;

import com.edev.support.dsl.Property;
import com.edev.support.entity.Entity;
import lombok.Data;

import java.util.*;

/**
 * 帮助数据访问类DAO访问数据库的数据实体类。
 * @author fangang
 */
@Data
public class DaoEntity {
	private static final String KEY = "key";
	private static final String VALUE = "value";
	private String tableName;
	//conditionMap: a list of conditions like: [{key:"col0",opt:'=',value:"val0"},{key:"col1",opt:'=',value:"val1"}]
	private List<Map<Object, Object>> conditionMap = new ArrayList<>();
	private List<Map<Object, Object>> pkMap = new ArrayList<>();
	public void addConditionMap(Map<Object, Object> conditionMap) { this.conditionMap.add(conditionMap); }
	public void addPkMap(Map<Object, Object> pkMap) { this.pkMap.add(pkMap); }
    /**
     * 将实体的所有属性及其值，与数据库表的列名的映射，进行相应的配置。
	 * <p>
     * 处理逻辑：
     * 1. 遍历每个属性及其相关的配置
     * 2. 获取实体属性及其相关的值，并过滤掉空值
     * 3. 构建列-值映射关系，写入conditionMap
     * 4. 主键字段的映射关系还单独记录到pkMap
     * @param entity 领域实体对象（携带数据）
     * @param properties 属性与列的映射关系的配置列表
     */
    public void setProperties(Entity<?> entity, List<Property> properties) {
		for(Property property : properties) {
			String name = property.getName();
			String column = property.getColumn();
			Object value = entity.getValue(name);

			if(value==null) continue;
			Map<Object, Object> map = new HashMap<>();
			map.put(KEY, column);
			map.put(VALUE, value);
			this.addConditionMap(map);

			if(property.isPrimaryKey()) this.addPkMap(map);
		}
	}

	/**
	 * 如果是主键字段，将其从conditionMap中移除。
	 */
	public void removePkFromConditionMap() {
		List<Map<Object, Object>> list = new ArrayList<>();
		for(Map<Object, Object> col : conditionMap) {
			boolean isAvailable = true;
			for (Map<Object, Object> pk : pkMap)
				if (col.get("key") == pk.get("key")) {
					isAvailable = false;
					break;
				}
			if(isAvailable) list.add(col);
		}
		conditionMap = list;
	}
}
